<?php
/**
 * Created by PhpStorm.
 * User: Liu
 * Date: 2023/2/27
 * Time: 11:47
 */

namespace app\admin\model;

use app\admin\common\Base;
use app\admin\validate\SeoLink;
use think\Db;
use think\Model;

class CategoryProduct extends Model {
    protected $table = 'qa_category_product';

    protected $insert = ['status','is_recommended','create_time','update_time'];
    protected $update = ['status','is_recommended','update_time'];

    public function add($data){
        $data = $this->handleData($data,'add');
        if ($data['code'] == 'suc') {
            //写入数据库记录
            $result = self::allowField(true)->create($data['data']);
            if ($result){
                insert_system_log('新增产品分类：' . $result);
                return ['code' => 'suc', 'msg' => config('msg.add_suc')];
            }else{
                return ['code' => 'err','msg' => config('msg.err_msg')];
            }
        }
        return ['code'=>$data['code'],'msg'=>$data['msg']];
    }

    public function edit($id,$data){
        $data = $this->handleData($data,'edit',$id);

        if ($data['code'] == 'suc') {
            //更新数据库记录
            $result = self::save($data['data'], ['id' => $id]);
            if ($result) {
                insert_system_log('编辑产品分类：' . $id);
                return ['code' => 'suc', 'msg' => config('msg.edit_suc')];
            } else {
                return ['code' => 'err', 'msg' => config('msg.err_msg')];
            }
        }
        return ['code'=>$data['code'],'msg'=>$data['msg']];
    }

    protected function handleData($data,$action,$id = ''){
        if (!empty($data['seo_link'])){
            $link_validate = new SeoLink();
            $base = new Base();
            if (!$link_validate->check($data)){
                //链接格式错误
                return ['code'=>'err','msg'=>$link_validate->getError()];
            }

            if ($action == 'add') {
                //新增操作
                $data['seo_link'] = $base->handleSeoUrl($data['seo_link'], 'category_product', 'add');
            } else {
                //修改操作
                $data['seo_link'] = $base->handleSeoUrl($data['seo_link'], 'category_product', 'edit',$id);
            }
        } else {
            $data['seo_link'] = null;
        }

        $data['level'] = $this->level(intval($data['pid']))+1;
        return ['code'=>'suc','data'=>$data];
    }

    public function level($pid,$level = 0){

        if ($pid !== 0){
            $level++;

            $parent = $this->db('category_product')
                ->where('id',$pid)
                ->field('id,pid')
                ->find();
            if ($parent['pid'] !== 0){
                $level = $this->level($parent['pid'],$level);
            }
        }

        return $level;
    }

    public function getAll(){
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $list = Db::name('category_product')
            ->where($where)
            ->field('id,pid,name,level')
            ->order('sort','asc')
            ->select();

        $related_list = [];
        foreach ($list as $k => $v){


            $list[$k]['value'] = intval($v['id']);
            $list[$k]['title'] = $v['name'];
            $list[$k]['disabled'] = "";
            $list[$k]['checked'] = "";


            if ($v['level'] == 2) {
                array_push($related_list,$list[$k]);
            }
        }

        return ['all' => $list, 'related' => $related_list];
    }

    protected function setStatusAttr($value){
        return empty($value) ? 0 : 1;
    }

    protected function setIsRecommendedAttr($value){
        return empty($value) ? 0 : 1;
    }

    protected function setCreateTimeAttr(){
        return time();
    }

    protected function setUpdateTimeAttr(){
        return time();
    }
}